import 'package:flutter/material.dart';
import '../../core/elegance_theme.dart';

/// 标签页位置枚举
enum ETabPosition {
  top,
  right,
  bottom,
  left,
}

/// 标签页类型枚举
enum ETabType {
  card,
  borderCard,
}

/// 标签页大小枚举
enum ETabSize {
  large,
  medium,
  small,
}

/// 标签页面板组件
class ETabPane extends StatelessWidget {
  /// 创建标签页面板
  const ETabPane({
    super.key,
    required this.label,
    required this.name,
    required this.child,
    this.disabled = false,
    this.icon,
  });

  /// 标签文本
  final String label;

  /// 标签名，与tabs的activeName对应
  final String name;

  /// 标签页内容
  final Widget child;

  /// 是否禁用
  final bool disabled;
  
  /// 标签图标
  final Widget? icon;

  @override
  Widget build(BuildContext context) {
    // 标签页面板通常不会直接渲染自身
    // 它的内容会被父组件ETabs根据activeName选择性渲染
    return child;
  }
}

/// 标签页容器组件
class ETabs extends StatefulWidget {
  /// 创建标签页容器
  const ETabs({
    super.key,
    required this.children,
    this.activeName,
    this.type = ETabType.card,
    this.position = ETabPosition.top,
    this.size = ETabSize.medium,
    this.closable = false,
    this.addable = false,
    this.editable = false,
    this.bottomBorder = false,
    this.onTabClick,
    this.onTabClose,
    this.onTabAdd,
    this.onTabRemove,
    this.onTabEdit,
  });

  /// 标签页面板列表
  final List<ETabPane> children;

  /// 当前激活的标签名
  final String? activeName;

  /// 标签页类型
  final ETabType type;

  /// 标签页位置
  final ETabPosition position;

  /// 标签页大小
  final ETabSize size;

  /// 是否可关闭
  final bool closable;

  /// 是否可添加
  final bool addable;

  /// 是否可编辑（可添加、可关闭）
  final bool editable;
  
  /// 底部是否显示边框
  final bool bottomBorder;

  /// 标签点击事件回调
  final Function(String name, String label)? onTabClick;

  /// 标签关闭事件回调
  final Function(String name)? onTabClose;

  /// 标签添加事件回调
  final Function()? onTabAdd;

  /// 标签移除事件回调
  final Function(String name)? onTabRemove;

  /// 标签编辑事件回调
  final Function(String? targetName, String action)? onTabEdit;

  @override
  State<ETabs> createState() => _ETabsState();
}

class _ETabsState extends State<ETabs> {
  late String _activeName;

  @override
  void initState() {
    super.initState();
    // 初始化当前激活的标签名
    if (widget.activeName != null) {
      _activeName = widget.activeName!;
    } else if (widget.children.isNotEmpty) {
      _activeName = widget.children.first.name;
    }
  }

  @override
  void didUpdateWidget(ETabs oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 如果外部传入的activeName发生变化，更新内部状态
    if (widget.activeName != null && widget.activeName != oldWidget.activeName) {
      setState(() {
        _activeName = widget.activeName!;
      });
    }
  }

  /// 处理标签点击
  void _handleTabClick(ETabPane tab) {
    if (tab.disabled) return;
    
    setState(() {
      _activeName = tab.name;
    });
    
    widget.onTabClick?.call(tab.name, tab.label);
  }

  /// 处理标签关闭
  void _handleTabClose(BuildContext context, ETabPane tab, TapDownDetails details) {
    
    if (tab.disabled) return;
    
    widget.onTabClose?.call(tab.name);
    widget.onTabRemove?.call(tab.name);
    widget.onTabEdit?.call(tab.name, 'remove');
    
    // 如果关闭的是当前激活的标签，激活第一个可用的标签
    if (_activeName == tab.name && widget.children.length > 1) {
      final newActiveTab = widget.children.firstWhere(
        (t) => t.name != tab.name && !t.disabled,
        orElse: () => widget.children.first,
      );
      
      setState(() {
        _activeName = newActiveTab.name;
      });
    }
  }

  /// 处理添加标签
  void _handleTabAdd() {
    widget.onTabAdd?.call();
    widget.onTabEdit?.call(null, 'add');
  }

  /// 构建单个标签按钮
  Widget _buildTabButton(BuildContext context, ETabPane tab, EleganceThemeData theme) {
    final isActive = _activeName == tab.name;
    final isDisabled = tab.disabled;
    
    // 根据类型获取不同的样式
    Color bgColor = Colors.transparent;
    Color borderColor = theme.borderColor;
    Color textColor = isDisabled ? theme.textPlaceholderColor : theme.textRegularColor;
    
    // 根据类型和选中状态设置不同的样式
    if (widget.type == ETabType.card) {
      if (isActive) {
        bgColor = theme.primaryColor;
        textColor = Colors.white;
        borderColor = Colors.white; // 选中时使用白色边框，与主色背景形成对比
      }
    } else if (widget.type == ETabType.borderCard) {
      if (isActive) {
        textColor = theme.primaryColor;
        borderColor = theme.primaryColor;
      }
    }
    
    // 根据size属性获取不同的内边距和图标大小
    EdgeInsets padding;
    double iconSize;
    double closeIconSize = 14;
    
    switch (widget.size) {
      case ETabSize.large:
        padding = const EdgeInsets.symmetric(horizontal: 20, vertical: 12);
        iconSize = 18;
        break;
      case ETabSize.small:
        padding = const EdgeInsets.symmetric(horizontal: 12, vertical: 6);
        iconSize = 14;
        closeIconSize = 12;
        break;
      case ETabSize.medium:
      default:
        padding = const EdgeInsets.symmetric(horizontal: 16, vertical: 10);
        iconSize = 16;
        break;
    }
    
    // 构建标签内容
    final List<Widget> tabContents = [];
    
    // 如果有图标，添加图标
    if (tab.icon != null) {
      tabContents.add(
        Container(
          width: iconSize,
          height: iconSize,
          alignment: Alignment.center,
          child: IconTheme(
            data: IconThemeData(
              color: textColor,
              size: iconSize,
            ),
            child: tab.icon!,
          ),
        ),
      );
      tabContents.add(const SizedBox(width: 6));
    }
    
    // 添加标签文本
    tabContents.add(
      Text(
        tab.label,
        style: TextStyle(color: textColor),
        overflow: TextOverflow.ellipsis,
      ),
    );
    
    // 如果可关闭或可编辑，添加关闭按钮
    if ((widget.closable || widget.editable) && !isDisabled) {
      tabContents.add(const SizedBox(width: 4));
      tabContents.add(
        GestureDetector(
          onTapDown: (details) => _handleTabClose(context, tab, details),
          child: Icon(
            Icons.close,
            size: closeIconSize,
            color: textColor,
          ),
        ),
      );
    }
    
    // 根据类型和选中状态决定是否显示边框
    Border? border;
    if (widget.type == ETabType.card && isActive) {
      // card类型：只有选中时有边框
      border = Border.all(color: borderColor);
    } else if (widget.type == ETabType.borderCard && !isActive) {
      // borderCard类型：只有未选中时有边框
      border = Border.all(color: borderColor);
    }
    
    // 构建标签按钮
    return GestureDetector(
      onTap: () => _handleTabClick(tab),
      child: Container(
        padding: padding,
        decoration: BoxDecoration(
          color: bgColor,
          border: border,
          borderRadius: BorderRadius.circular(4),
        ),
        child: Row(
          children: tabContents,
        ),
      ),
    );
  }

  /// 构建标签栏
  Widget _buildTabBar(BuildContext context) {
    final EleganceThemeData theme = EleganceTheme.of(context);
    final List<Widget> tabButtons = [];

    // 添加所有标签按钮
    for (final tab in widget.children) {
      tabButtons.add(_buildTabButton(context, tab, theme));
      tabButtons.add(const SizedBox(width: 4));
    }
    
    // 如果可添加或可编辑，添加添加按钮
    if ((widget.addable || widget.editable)) {
      tabButtons.add(
        GestureDetector(
          onTap: _handleTabAdd,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
            decoration: BoxDecoration(
              color: Colors.transparent,
              border: Border.all(color: theme.borderColor),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Icon(
              Icons.add,
              size: 16,
              color: theme.textRegularColor,
            ),
          ),
        ),
      );
    }
    
    // 根据位置构建标签栏布局
    Widget tabBar;
    
    switch (widget.position) {
      case ETabPosition.top:
      case ETabPosition.bottom:
        tabBar = SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Row(children: tabButtons),
        );
        break;
      case ETabPosition.left:
      case ETabPosition.right:
        tabBar = SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Column(children: tabButtons),
        );
        break;
    }
    
    return tabBar;
  }

  /// 构建标签页内容
  Widget _buildTabContent() {
    // 查找当前激活的标签页
    final activeTab = widget.children.firstWhere(
      (tab) => tab.name == _activeName,
      orElse: () => widget.children.isNotEmpty ? widget.children.first : const ETabPane(label: '', name: '', child: SizedBox()),
    );
    
    // 根据位置构建整体布局
    return activeTab.child;
  }

  @override
  Widget build(BuildContext context) {
    final EleganceThemeData theme = EleganceTheme.of(context);
    
    // 构建整体布局
    Widget tabsLayout;
    
    switch (widget.position) {
      case ETabPosition.top:
        tabsLayout = Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildTabBar(context),
            const SizedBox(height: 8),
            _buildTabContent(),
          ],
        );
        break;
      case ETabPosition.bottom:
        tabsLayout = Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildTabContent(),
            const SizedBox(height: 8),
            _buildTabBar(context),
          ],
        );
        break;
      case ETabPosition.left:
        tabsLayout = Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildTabBar(context),
            const SizedBox(width: 8),
            Expanded(child: _buildTabContent()),
          ],
        );
        break;
      case ETabPosition.right:
        tabsLayout = Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(child: _buildTabContent()),
            const SizedBox(width: 8),
            _buildTabBar(context),
          ],
        );
        break;
    }
    
    // 构建基础边框装饰
    BoxDecoration? decoration;
    
    if (widget.type == ETabType.borderCard) {
      decoration = BoxDecoration(
        border: Border.all(color: theme.borderColor),
        borderRadius: BorderRadius.circular(4),
      );
    } else if (widget.bottomBorder) {
      decoration = BoxDecoration(
        border: Border(
          bottom: BorderSide(color: theme.borderColor),
        ),
      );
    } else {
      // 默认不显示任何边框
      decoration = null;
    }
    
    // 应用容器样式
    return Container(
      decoration: decoration,
      padding: widget.type == ETabType.borderCard ? const EdgeInsets.all(8) : EdgeInsets.zero,
      child: tabsLayout,
    );
  }
}